//
//  PictureViewController.swift
//  微博三天
//
//  Created by jessica on 15/11/19.
//  Copyright © 2015年 jessica. All rights reserved.
//


//(1)在AppDelegate里面设置当前为根控制器,最后换回来
import UIKit

import SnapKit
//(2)列数
private let cloumn : CGFloat = 4
//(2)间隔
private let pictureMargin : CGFloat = 10
//(21)限制最多可添加数量的
private let maxImageCount = 3

private let reuseIdentifier = "Cell"

class PictureViewController: UICollectionViewController {
    
    
    
    //(16)添加图片数组属性
     lazy var imageList = [UIImage]()
    
    
    init() {
        
        //(3)构造方法
        let layout = UICollectionViewFlowLayout()
        //一个的宽
        let w = (screenW - (cloumn + 1) * pictureMargin) / cloumn
        layout.minimumInteritemSpacing = pictureMargin
        layout.minimumLineSpacing = pictureMargin
        layout.itemSize = CGSize(width: w, height: w)
    
        //设置section间距,这里不写的话会影响删除按钮的点击
        layout.sectionInset = UIEdgeInsets(top: pictureMargin, left: pictureMargin, bottom: 0, right: pictureMargin)
        
        //指定的构造函数
        super.init(collectionViewLayout: layout)
 
    }
    //尾随屁股后面
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
//        self.view.backgroundColor = UIColor.whiteColor()
        //(5)让这里的UIConllectionViewCell->PictureSelectorCell
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        //(17)随着添加数量增加
//        return imageList.count + 1
        //(22)限制图片数量,不等于最多图片数量就加1,等于就加0
        let add = (imageList.count == maxImageCount) ? 0 : 1
        return imageList.count + add
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //(5) 增加 as?PictureSelectorCell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)as! PictureSelectorCell
        
        //接受代理者
        cell.selectorCellDelegate = self
        
        cell.backgroundColor = UIColor.randomColor()
        //(19)绑定数据源
        if indexPath.item == imageList.count{
        
        cell.image = nil
        }
        else{
        
        cell.image = imageList[indexPath.item]
        
        }
        
        return cell
    }
    
    
}


//(8)扩展 代理 ,如果系统有代理的方法就用,没有的话就创建一个,不如上一个UITextViewDelegate是系统的就不用了

extension PictureViewController : PictureSelectorCellDelegate{
    
    //(25)修改添加cell : PictureSelectorCell,不然图片不能添加咯
    func userWillAddPicture(cell : PictureSelectorCell) {
        //(27)有图片就不能点击添加不会超过最多限制而继续添加的情况,必须return ,必须的
        if cell.image != nil {
        print("添加图片")
            return
            
        }
        //(13)使用系统的图片选择器
        let picker = UIImagePickerController()
    //(12)指定代理
        picker.delegate = self
        
        //是否允许编辑 在上传头像的时候 需要打开
//        picker.allowsEditing = true
//
        presentViewController(picker, animated: true, completion: nil)
        
        
    }
    func userWillDelectPicture(cell : PictureSelectorCell) {
        
        print("删除图片")
        
        //(23)获取点击cell的indexPath 取操作数组 有提示要cell
//        let indexPath = collectionView?.indexPathForCell(<#T##cell: UICollectionViewCell##UICollectionViewCell#>)
        let indexPath = collectionView?.indexPathForCell(cell)
        //取消删除当前
        self.imageList.removeAtIndex(indexPath!.item)
        //刷新视图,顺便给个动画,缓慢消失
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            //开始
            cell.alpha = 0
            }) { (_) -> Void in
                //完成结束
                cell.alpha = 1
                //刷新
                self.collectionView?.reloadData()
                
        }
    }
}

//(14)扩展 遵守图片选择器协议
extension PictureViewController : UIImagePickerControllerDelegate ,UINavigationControllerDelegate {
    func  imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        print(picker)
//        print(editingInfo)
        
        //(20)添加图片到数组中,刷新collectionView
        imageList.append(image)
        collectionView?.reloadData()
        
        //(15)一旦实现协议方法 ,dismiss就交给程序员
 self.dismissViewControllerAnimated(true, completion: nil)
    }
}




//(9)代理的协议
@objc protocol PictureSelectorCellDelegate : NSObjectProtocol {
    
    //定义协议方法 ,(24)添加cell : PictureSelectorCell,原来是()初始化
    optional func userWillAddPicture(cell : PictureSelectorCell)
    //(24)
    optional func userWillDelectPicture( cell : PictureSelectorCell)
    
}
//(5)创建建一个Cell的类方法
class PictureSelectorCell : UICollectionViewCell {
    
    weak var selectorCellDelegate : PictureSelectorCellDelegate?
    
    //(10)代理实现
    @objc private func addBtnDidClick(){
        
        //(26)添加self就是PictureSelectorCell的意思咯
        selectorCellDelegate?.userWillAddPicture?(self)
        
    }
    @objc private func deleteBtnDidClick(){
        //(26)
        selectorCellDelegate?.userWillDelectPicture?(self)
        
    }
    
    //定义图片数据模型
    
    var image : UIImage?{
    
        didSet{
        //18)这个是没有图片,也就是等待添加的那个隐藏删除,不然会崩的
        delectBtn.hidden = (image == nil)
            if image != nil{
            
            AddBtn.setBackgroundImage(image, forState: .Normal)
            }
            else{
            
                AddBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
        
    
    }
   
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置UI(6)
    private func setupUI() {
        //添加
        contentView.addSubview(AddBtn)
        contentView.addSubview(delectBtn)
        //约束
        AddBtn.snp_makeConstraints { (make) -> Void in
        
            make.edges.equalTo(contentView.snp_edges)
        }
        delectBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
            
        }
        
        //(7)添加点击事件
        AddBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        delectBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
    }
    //(4)懒加载控件 ,一个加号 ,一个删除标识  UIButton+Extension中修改一下,title可空
    private lazy var delectBtn : UIButton = UIButton(title: nil, color: nil, backImage: "compose_photo_close")
    private lazy var AddBtn : UIButton = UIButton(title: nil, color: nil, backImage: "compose_pic_add")
    
    
}





